package com.star.oauth.controller;

import com.star.oauth.entity.dto.TokenResult;
import com.star.oauth.entity.param.RefreshTokenParam;
import com.star.oauth.service.OAuthService;
import lombok.extern.slf4j.Slf4j;
import org.apache.oltu.oauth2.as.issuer.MD5Generator;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuer;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class RefreshTokenController {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private OAuthService oAuthService;



    @RequestMapping("/refreshToken")
    public Object getRefreshToken(@RequestBody RefreshTokenParam refreshTokenParam){

        //验证clientId信息
        //验证 grantype 类型 OAuth.OAUTH_GRANT_TYPE
        if(refreshTokenParam.getGrantype() == null && !GrantType.REFRESH_TOKEN.toString().equals(refreshTokenParam.getGrantype()))
            throw new RuntimeException("无效的GRANT_TYPE");
        String refreshToken = refreshTokenParam.getRefreshToken();

        String username = oAuthService.getUsernameByRefresh(refreshToken);
        if(StringUtils.isEmpty(username)) throw new RuntimeException("无效的REFRESH_TOKEN或者REFRESH_TOKEN不存在");

        OAuthIssuer oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
        TokenResult tokenResult = new TokenResult();
        try {
            tokenResult.setAccess_token(oauthIssuerImpl.accessToken());
            tokenResult.setRefresh_token(oauthIssuerImpl.refreshToken());
            tokenResult.setExpire_in(3600);
            tokenResult.setRefreshtoken_expire_in(7200);
            oAuthService.addAccessToken(tokenResult.getAccess_token(),username);
            oAuthService.addRefreshToken(tokenResult.getRefresh_token(),username);
        } catch (OAuthSystemException e) {
            e.printStackTrace();
        }
        return tokenResult;
    }
}
